package com.laker.autotest.desktop;

import com.formdev.flatlaf.FlatLightLaf;
import com.github.kwhat.jnativehook.GlobalScreen;

import javax.swing.*;
import java.awt.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ScriptRecorderApp {
    private final JTextArea eventTextArea = new JTextArea();
    private final EventListModel eventListModel = new EventListModel(eventTextArea);
    private final JScrollPane eventScrollPane = new JScrollPane(eventTextArea);
    private final JButton recordBtn = new JButton("开始录制");
    private final JButton stopBtn = new JButton("停止录制");
    private final JButton saveBtn = new JButton("保存脚本");
    private final JButton playbackBtn = new JButton("回放脚本");
    private final ScriptService scriptService = new ScriptService(eventListModel);
    private final EventListenerManager eventListenerManager = new EventListenerManager(eventListModel);

    public ScriptRecorderApp() {
        try {
            UIManager.setLookAndFeel(new FlatLightLaf());
        } catch (Exception ex) {
            System.err.println("FlatLaf 初始化失败: " + ex);
        }
        JFrame frame = new JFrame("脚本录制器");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(600, 400);
        frame.setLocationRelativeTo(null); // 居中显示
        JPanel buttonBar = new JPanel();
        buttonBar.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 10));
        buttonBar.add(recordBtn);
        buttonBar.add(stopBtn);
        buttonBar.add(saveBtn);
        buttonBar.add(playbackBtn);
        // 搜索框
        JTextField searchField = new JTextField(20);
        JButton searchBtn = new JButton("搜索");
        buttonBar.add(searchField);
        buttonBar.add(searchBtn);
        eventTextArea.setEditable(false);
        eventTextArea.setFont(new Font("Monospaced", Font.PLAIN, 14));
        frame.setLayout(new BorderLayout());
        frame.add(buttonBar, BorderLayout.NORTH);
        frame.add(eventScrollPane, BorderLayout.CENTER);
        recordBtn.addActionListener(e -> eventListenerManager.startRecord());
        stopBtn.addActionListener(e -> eventListenerManager.stopRecord());
        saveBtn.addActionListener(e -> scriptService.saveScript(eventListenerManager.getScriptEvents()));
        playbackBtn.addActionListener(e -> scriptService.playbackScript());
        // 搜索功能：高亮匹配内容
        searchBtn.addActionListener(e -> {
            String keyword = searchField.getText();
            if (keyword == null || keyword.isEmpty()) return;
            String text = eventTextArea.getText();
            int idx = text.indexOf(keyword);
            if (idx >= 0) {
                eventTextArea.requestFocus();
                eventTextArea.select(idx, idx + keyword.length());
            } else {
                JOptionPane.showMessageDialog(frame, "未找到: " + keyword, "搜索结果", JOptionPane.INFORMATION_MESSAGE);
            }
        });
        // 支持双击复制最后一行到剪贴板
        eventTextArea.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                if (evt.getClickCount() == 2) {
                    String text = eventTextArea.getText();
                    String[] lines = text.split("\n");
                    if (lines.length > 0) {
                        String lastLine = lines[lines.length - 1];
                        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new java.awt.datatransfer.StringSelection(lastLine), null);
                        JOptionPane.showMessageDialog(eventTextArea, "已复制到剪贴板", "提示", JOptionPane.INFORMATION_MESSAGE);
                    }
                }
            }
        });
        frame.setVisible(true);

        try {
            if (!GlobalScreen.isNativeHookRegistered()) {
                Logger logger = Logger.getLogger(GlobalScreen.class.getPackage().getName());
                logger.setLevel(Level.OFF);
                logger.setUseParentHandlers(false);
                GlobalScreen.registerNativeHook();
            }
        } catch (Exception e) {
            return;
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(ScriptRecorderApp::new);
    }
}